package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;
import static com.hmdp.utils.SystemConstants.USER_TOKEN_PREFIX;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor,ApplicationContextAware {
//    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if(token==null){
            response.setStatus(401);
            return false;
        }
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(USER_TOKEN_PREFIX + token);
        if(map.isEmpty()){
            response.setStatus(401);
            return false;
        }
        //保存到ThreadLocal
        UserDTO userDTO = BeanUtil.fillBeanWithMap(map, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
          UserHolder.removeUser();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
                stringRedisTemplate=applicationContext.getBean(StringRedisTemplate.class);
    }
}
